use crate::models::article_tags::{CreateParams, Model};
use axum::debug_handler;
use loco_rs::prelude::*;

#[debug_handler]
async fn create(
    State(ctx): State<AppContext>,
    Json(params): Json<CreateParams>,
) -> Result<Response> {
    let article_tag = Model::create(&ctx.db, &params).await?;
    format::json(article_tag)
}

#[debug_handler]
async fn find_by_id(State(ctx): State<AppContext>, Path(id): Path<String>) -> Result<Response> {
    let article_tag = Model::find_by_id(&ctx.db, &id).await?;
    format::json(article_tag)
}

#[debug_handler]
async fn find_by_article_id(
    State(ctx): State<AppContext>,
    Path(article_id): Path<String>,
) -> Result<Response> {
    let article_tags = Model::find_by_article_id(&ctx.db, &article_id).await?;
    format::json(article_tags)
}

#[debug_handler]
async fn find_by_tag_id(
    State(ctx): State<AppContext>,
    Path(tag_id): Path<String>,
) -> Result<Response> {
    let article_tags = Model::find_by_tag_id(&ctx.db, &tag_id).await?;
    format::json(article_tags)
}

#[debug_handler]
async fn delete_by_id(State(ctx): State<AppContext>, Path(id): Path<String>) -> Result<Response> {
    let article_tag = Model::find_by_id(&ctx.db, &id).await?;
    article_tag.delete(&ctx.db).await?;
    format::json(())
}

pub fn routes() -> Routes {
    Routes::new()
        .prefix("article-tags")
        .add("/", post(create))
        .add("/:id", get(find_by_id))
        .add("/article/:article_id", get(find_by_article_id))
        .add("/tag/:tag_id", get(find_by_tag_id))
        .add("/:id", delete(delete_by_id))
}
